package servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Сервлет-раздатчик, выполняет функции приемки запрос от клиента, контроль за
 * аутентификацией пользователя и перенаправления (forwarding) запроса
 * соответствующей JSP или сервлету.
 *
 * @author Konstantin Chumachenko <kostyachum@gmail.com>
 */
public class DispatcherServlet extends HttpServlet {

    @Override
    protected void doPost(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        String ajax = request.getParameter("ajax");
        String direction = request.getParameter("p");
        String forward = "/phonebook.jsp";

        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        System.out.println(username);
        if (direction != null) {
            if (direction.equals("admin") && username!=null) {
                forward = "/admin.jsp";
            }else{
                forward = "/login.jsp";
            }
        }
        if (ajax != null) {
            if (ajax.equals("admin")) {
                forward = "/adminServlet";
            } else {
                forward = "/phoneServlet";
            }
        }
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(forward);
        dispatcher.forward(request, response);
    }

    @Override
    protected void doGet(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}
